//
//  PanelVC.swift
//  sandboxapp
//
//  Created by 杨岑 on 2018/8/31.
//  Copyright © 2018年 杨岑. All rights reserved.
//

import Cocoa

class PanelVC: NSViewController {

    typealias CompletionHandler = (_: Any) -> Void
    
    @IBOutlet weak var progressBar: NSProgressIndicator!

    var completionHandler: CompletionHandler?
    
    private var stopped = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Start background work in an operation queue.
        OperationQueue().addOperation {
            do {
                try self.backgroundWork()
            } catch {
                print(error)
            }
            
            // Perform final check in main thread for serial operation.
            OperationQueue.main.addOperation {
                // If background work finished without interruption...
                if !self.stopped {
                    self.presentingViewController?.dismiss(self)
                }
            }
        }
    }
    
    override func viewDidAppear() {
        super.viewDidAppear()
        self.view.window?.title = "Modal Window"
    }
    
    override func viewWillDisappear() {
        super.viewWillDisappear()
        self.stopped = true
    }
    
    override func viewDidDisappear() {
        super.viewDidDisappear()
        self.completionHandler?(self)
    }
    
    private func backgroundWork() throws {
        var progress = 0.0
        while !self.stopped {
            OperationQueue.main.addOperation {
                self.progressBar.increment(by: 1.0)
                progress = self.progressBar.doubleValue
            }
            if progress >= 100 {break}
            Thread.sleep(forTimeInterval: 0.03)
        }
    }
    
    @IBAction func dismiss_click(_ sender: Any) {
        self.stopped = true
        self.presentingViewController?.dismiss(self)
    }
}
